package com.haitaoit.chengquan.module.home.activity.forum;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.QBaseActivity;
import com.haitaoit.chengquan.bean.ImgObj;
import com.haitaoit.chengquan.business.data.PublicPostHttp;
import com.haitaoit.chengquan.business.data.PublicPostTypeHttp;
import com.haitaoit.chengquan.business.http.bean.ParamObj;
import com.haitaoit.chengquan.business.request.PublicPostReq;
import com.haitaoit.chengquan.business.request.ReqImgObj;
import com.haitaoit.chengquan.module.home.adapter.forum.QImageAdapter;
import com.haitaoit.chengquan.module.home.model.TitleModel;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.utils.BitmapUtils;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.TakeImage;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/8.
 */

public class QPostForumActivity extends QBaseActivity implements View.OnClickListener {
    private ImageView  back;
    private TextView   forum_type;
    private EditText   add_forum_title;
    private EditText   add_forum_content;
    private MyGridView myGridView;
    private TextView   send_btn;

    private QImageAdapter    adapter;
    private List<TitleModel> titleModels;

    //这里设置为默认的数值条目选择，
    private String           type_id = "0";
    private int              curImg_index;

    private TakeImage takeImage;
    //进行选择
    private String mTextName = "";

    @Override
    public int getContentView() {
        return R.layout.activity_qpost_forum;
    }

    @Override
    public void initView() {
        back = (ImageView) findViewById(R.id.back);
        forum_type = (TextView) findViewById(R.id.forum_type);
        add_forum_title = (EditText) findViewById(R.id.add_forum_title);
        add_forum_content = (EditText) findViewById(R.id.add_forum_content);
        myGridView = (MyGridView) findViewById(R.id.myGridView);
        send_btn = (TextView) findViewById(R.id.send_btn);
        adapter = new QImageAdapter(this);
        adapter.getDataList().add(new ImgObj(0, 0, null, null));
        myGridView.setAdapter(adapter);
        takeImage = new TakeImage(this, handler, false);

        //这里不能进行intent传递数据
//        mTextName = PreferenceUtils.getPrefString(this, "text_name", "");

        Intent intent = getIntent();

        if (intent!=null){
            mTextName = intent.getStringExtra("text_name");
        }else {
            mTextName = "";
        }

        //这里判断进来选择默认，如果不是默认的全部，设置为可选的其他分类，如果已经选择了分类，这里设置为不可用来进行不选择其他分类
        if (TextUtils.equals(mTextName, "全部") || TextUtils.isEmpty(mTextName)) {
            forum_type.setText("设备维修");
            forum_type.setEnabled(true);
        } else {
            forum_type.setText(mTextName);
            forum_type.setEnabled(false);
            if (TextUtils.equals("设备维修",mTextName)){
                type_id = "1";
            }else if(TextUtils.equals("资料共享",mTextName)){
                type_id = "2";
            }else if(TextUtils.equals("行业动态",mTextName)){
                type_id = "3";
            }else if(TextUtils.equals("加工订单",mTextName)){
                type_id = "4";
            }
        }


    }

    @Override
    public void initData() {
        new PublicPostTypeHttp(this, handler, GetNotParam(), 1);
    }

    @Override
    public void initEvent() {
        back.setOnClickListener(this);
        send_btn.setOnClickListener(this);
        forum_type.setOnClickListener(this);
        adapter.setBackCall(new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                super.deal(which, obj);
                curImg_index = (Integer) obj[0];
                takeImage.showDialog();

            }
        });


        takeImage.setOnPictureListener(new TakeImage.PictureListener() {
            @Override
            public void pictureCall(String path) {

                ImgObj imgObj = adapter.getDataList().get(curImg_index);
                imgObj.setLocImgPath(path);
                imgObj.setHaveImg(2);

                if (adapter.getDataList().size() < 3)
                    adapter.getDataList().add(new ImgObj(0, 0, null, null));
                sendMsg(handler, 2, null);
            }
        });
    }

    @Override
    protected void updateUI(Message msg) {
        switch (msg.what) {
            case 1:
                titleModels = (List<TitleModel>) msg.obj;
                closeProgressDialog();
                break;
            case 2:
                adapter.notifyDataSetChanged();
                break;
            case 3:
                closeProgressDialog();
                ToastUtils.showToast( QPostForumActivity.this.getString(R.string.QPostForumActivity_send_success));
                finish();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.forum_type:

                updateBigtype(titleModels);
                break;
            case R.id.send_btn:
                if (PreferenceUtils.getPrefString("user_id", "").equals("")) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                } else if (add_forum_title.getText().toString().equals("")) {
                    ToastUtils.showToast( "请输入标题！");
                } else if (add_forum_content.getText().toString().equals("")) {
                    ToastUtils.showToast( "请输入内容！");
                } else {
                    PublicPost();
                }
                break;
        }
    }

    private void PublicPost() {
        List<ParamObj> paramObjs = new ArrayList<ParamObj>();
        paramObjs.add(new ParamObj("user_id", PreferenceUtils.getPrefString("user_id", "")));
        paramObjs.add(new ParamObj("id", "0"));

        ArrayList<ReqImgObj> reqImgObjs = new ArrayList<ReqImgObj>();
        try {
            int length = adapter.getDataList().size();
            Bitmap upbitmap;
            for (int i = 0; i < length; i++) {
                if (i == (length - 1) && adapter.getDataList().get(i).getHaveImg() == 0)
                    break;
                //                reqImgObjs.add(new ReqImgObj(Base64Util.encodeBase64File(adapter.getDataList().get(i).getLocImgPath())));

                upbitmap = ImageLoader.getInstance().loadImageSync("file://" + adapter.getDataList().get(i).getLocImgPath());
                upbitmap = BitmapUtils.getSmallBitmap(upbitmap);
                reqImgObjs.add(new ReqImgObj(BitmapUtils.bitmapToString(upbitmap)));

            }
        } catch (Exception e) {
            ToastUtils.showToast(QPostForumActivity.this.getString(R.string.QPostForumActivity_img_switch_failure));
        }
        new PublicPostHttp(this, handler, GetHaveParam(paramObjs), new PublicPostReq(type_id, add_forum_title.getText().toString(), add_forum_content.getText().toString(), reqImgObjs), 3);
    }

    private void updateBigtype(final List<TitleModel> list) {
        final ArrayList<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "");
        popSex.setPicker(list2);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                forum_type.setText(list2.get(options1));
                type_id = list.get(options1).getId();
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(forum_type, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;// 0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takeImage.onActivityResult(requestCode, resultCode, data);
    }
}
